<template>
  <el-form label-position="top">
    <el-form-item
      :label="item.attr_name"
      v-for="item in manyGoodsList"
      :key="item.attr_id"
    >
      <el-checkbox-group v-model="item.attr_vals">
        <el-checkbox
          :label="item"
          v-for="(item, i) in item.attr_vals"
          :key="i"
          border
        ></el-checkbox>
      </el-checkbox-group>
    </el-form-item>
  </el-form>
</template>

<script>
import { getGoodsParamsListAPI } from '@/api'
import EventBus from '@/event-bus'
export default {
  name: 'GoodsParams',
  inject: ['addGoodsForm'],
  created() {
    this.loadingGoodsParams()
    EventBus.$on('push-attr', () => {
      this.pushParams()
    })
  },
  data() {
    return {
      manyGoodsList: []
    }
  },
  methods: {
    // 加载商品参数
    async loadingGoodsParams() {
      try {
        const { data } = await getGoodsParamsListAPI(
          this.addGoodsForm.goods_cat[2],
          'many'
        )
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('加载商品参数失败')
        }
        data.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(' ') : []
        })
        this.$message.success('加载商品参数成功')
        this.manyGoodsList = data.data
      } catch (error) {
        this.$message.error('加载商品参数失败')
      }
    },
    pushParams() {
      this.manyGoodsList.forEach(item =>
        this.addGoodsForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        })
      )
    }
  }
}
</script>

<style scoped lang="less">
.el-checkbox {
  margin: 5px 10px !important;
}
</style>
